package persistencia.xml.martin;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class xmlParser {
 
     
    private CSVList lista;  
	private Document doc;
    private Element raiz;
    private static DocumentBuilderFactory dbf;
    private static DocumentBuilder db;
   
 
      public xmlParser( CSVList l){
      
        lista = l;
        
      }
    
      
      
      
      public void xmlAbrirLectura( String ruta){
           
    	  	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           
            try {
                 
                  DocumentBuilder db = dbf.newDocumentBuilder();
                 
                  doc = db.parse(ruta);
                 
 
            }catch(ParserConfigurationException pce) {
                  pce.printStackTrace();
            }catch(SAXException se) {
                  se.printStackTrace();
            }catch(IOException ioe) {
                  ioe.printStackTrace();
            }
      }
 
      
      public void xmlAbrirEscritura( String nombreDocumento ) throws ParserConfigurationException
      {
    	  	dbf = DocumentBuilderFactory.newInstance () ; 
           
    	    dbf.setNamespaceAware ( true ) ; 
           
    	    db  = dbf.newDocumentBuilder () ; 
           
    	    doc = db.newDocument () ; 
       
    	    raiz = doc.createElementNS ( null, nombreDocumento ) ; 		 
    	    
    	    doc.appendChild(raiz);
    	      	  
     
      }
      
     
      public void xmlParsearDocumento(String tagRegistro)
      {
            //obtiene el elemeto principal raiz del xml
            Element elem = doc.getDocumentElement();
           
            //obtiene una lista de nodos del documento para el tag pedido
            NodeList listaNodos = elem.getElementsByTagName(tagRegistro);
            if(listaNodos != null && listaNodos.getLength() > 0) {
                  for(int i = 0 ; i < listaNodos.getLength();i++) {
                       
                        //captura un elemento de nodo xml
                        Element el = (Element)listaNodos.item(i);
                       
                        //lee el nodo y lo asigna al string 
                        String s = readData(el);
                        
                        //acumula el string en la lista final
                        lista.addElement(s);
                        
                  }
            }
      }
 
 
        private String readData(Element elem) {
           
    	  // lee el contenido de los campos de cada registro
    	  // los guarda en un String concatenados por ";"
        	
        	ArrayList<String> tag = lista.getListaParametros();			
        	
        	ArrayList<String> valores = new ArrayList<String>();
        	
        	Iterator<String> i = tag.iterator();
        	
        	while (i.hasNext())
        	{
        	 		valores.add(getTextValue(elem,i.next()));
        	}
    		
        	
        	String e = lista.crearRegistro(valores);
        	
        	
            return e;
      }
 

 
       private String getTextValue(Element ele, String tagName) {
            String textVal = null;
            NodeList nl = ele.getElementsByTagName(tagName);
            if(nl != null && nl.getLength() > 0) {
                  Element el = (Element)nl.item(0);
                  textVal = el.getFirstChild().getNodeValue();
            }
 
            return textVal;
      }
 

       public void xmlAgregar( ArrayList<String> listaValores, String tagRegistro) throws Exception
       {
  
    	   	   Element item;
    	   	   
    	   	   Element tag;
    	        	       	   
    	   	   ArrayList<String> tags = lista.getListaParametros();			
       	    	    	   
    	 	   tag = doc.createElementNS ( null, tagRegistro ) ; 		 
    	    
    		   Iterator<String> iTags =   tags.iterator();
    		 
    		   Iterator<String> iValues =  listaValores.iterator();
    			   
    		   while (iTags.hasNext()) {
    			
    			   item = doc.createElementNS ( null, iTags.next() ) ; 			
    		
    			   item.appendChild ( doc.createTextNode ( iValues.next() )) ; 
    			   
    			   tag.appendChild ( item ) ; 										
    		   }
    		   
    	       raiz.appendChild ( tag ) ; 	
    		   
    	   }
       
       
       
       
       public void xmlGuardar (String xmlRuta) throws Exception
       {
    	   	
    	       	   
    	   		TransformerFactory transformerFactory = TransformerFactory.newInstance();
    			
    			Transformer transformer = null;
				
    			transformer = transformerFactory.newTransformer();
				
    			DOMSource source = new DOMSource(doc);
    		
    			StreamResult result = new StreamResult(new File(xmlRuta));
    			
    			transformer.transform(source, result);
				
       }
       
       
       
       
       
    
    
}